<template>
	<view class="archives-add-page">
		<view class="main">
			<div class="main-container">
				<view class="header">
					<view class="step-list">
						<view class="step" v-for="(item, index) in arrowList" :key="index">
							<view class="step-box" :class="{ 'active': stepIndex >= index }">
								<view class="line"></view>
								<view class="circle"></view>
								<view class="text">{{ item }}</view>
							</view>
						</view>
					</view>
				</view>

				<view class="step-content">
					<view class="step-content-container">
						<scroll-view scroll-y="true" style="height:100%">
							<view class="base-info">
								<view class="base-info-tit">
									<text>案卷基本信息</text>
								</view>
								<view v-show="stepIndex == 0" class="step-item first-step">
									<u-form :model="form" ref="addForm" class="apply-form-field" label-width="150">
										<u-form-item label="档案名称" prop="name" required>
											<u-input v-model="form.name" placeholder="请输入" />
										</u-form-item>
										<u-form-item label="程序类型" prop="archivesType" required>
											<view class="tags-wrap">
												<u-tag class="tag" v-for="item in archivesTypeList" :text="item.label" :type="item.type" mode="dark" @click="onTagChange(item)" />
											</view>
										</u-form-item>
										<u-form-item label="案卷编号" prop="code" required>
											<u-input v-model="form.code" :disabled="!!params.id" />
										</u-form-item>
									</u-form>
								</view>
								<view v-if="stepIndex == 1" class="step-item second-step">
									<u-form :model="form" class="apply-form-field" label-width="150">
										<u-form-item label="" prop="weather">
											<view class="wrap">
												<view class="left-tit">
													<text>起火天气</text>
													<uni-icons @click="showTips" type="help" size="16">></uni-icons>
												</view>
												<u-input v-model="form.weather" />
											</view>
										</u-form-item>
										<u-form-item label="起火对象" prop="fireName">
											<u-input v-model="form.fireName" />
										</u-form-item>
										<u-form-item label="起火地址" prop="fireAddress">
											<u-input v-model="form.fireAddressText" style="margin-right: 10rpx;" />
											<button v-if="isNetworkConnected" class="mini-btn" type="default" plain="true" size="mini" @click="navTo('/pages/common/mapWebview')">选择地址</button>
										</u-form-item>
										<u-form-item label="详细地址" prop="address">
											<u-input v-model="form.address" />
										</u-form-item>
										<u-form-item label="报警时间" prop="callTime" right-icon="arrow-right">
											<u-input v-model="form.callTime" disabled @tap="onShowTimePicker('callTime')" />
										</u-form-item>
										<u-form-item label="出警时间" prop="goTime" right-icon="arrow-right">
											<u-input v-model="form.goTime" disabled @tap="onShowTimePicker('goTime')" />
										</u-form-item>
										<u-form-item label="承办单位" prop="doOrg">
											<u-input v-model="form.doOrg" />
										</u-form-item>
										<u-form-item label="主办人" prop="doPersonName" :right-icon="isNetworkConnected? 'arrow-right':''">
											<!-- v-model 展示的是 doPersonName，实际id 是 doPerson -->
											<u-input v-if="isNetworkConnected" v-model="form.doPersonName" placeholder="请选择" type="select" class="form-field-select" @tap="onShowPersonPopup('host')" />
											<u-input v-else v-model="form.doPersonName" />
										</u-form-item>
										<u-form-item label="协办人" prop="doOtherPersonName" :right-icon="isNetworkConnected? 'arrow-right':''">
											<!-- v-model 展示的是 doOtherPersonName，实际id 是 doOtherPerson -->
											<u-input v-if="isNetworkConnected" v-model="form.doOtherPersonName" placeholder="请选择" type="select" class="form-field-select" @tap="onShowPersonPopup('assist')" />
											<u-input v-else v-model="form.doOtherPersonName" />
										</u-form-item>
										<u-form-item label="出警车辆">
											<u-input v-model="form.doCars" type="number" />
										</u-form-item>
										<u-form-item label="出警人数">
											<u-input v-model="form.doPersonCount" type="number" />
										</u-form-item>
										<u-form-item label="简单描述">
											<u-input v-model="form.remark" />
										</u-form-item>
									</u-form>
								</view>
							</view>
						</scroll-view>
					</view>
				</view>

				<view class="footer">
					<view class="btns">
						<!-- <button @click="importData">导入</button> -->
						<button type="primary" :disabled="submitLoading" :loading="submitLoading" :ripple="true" @click="submit">提交</button>
						<button type="primary" :disabled="!isFormRequired" @click="nextStep">{{ stepIndex == 0 ?
							'下一步' : '上一步' }}</button>
					</view>
				</view>
			</div>
		</view>
		<u-toast ref="uToast" />
		<u-select v-model="fireInvestigationTypesObj.show" mode="single-column" :list="fireInvestigationTypesObj.list" @confirm="confirmArchivesType"></u-select>
		<u-picker mode="time" :defaultTime="timeObj.defaultStartTime" v-model="timeObj.show" :params="timeObj.params" @confirm="confirmTimePicker"></u-picker>
		<u-popup class="work-person-popup" v-model="workPersonObj.show" mode="bottom" border-radius="14" height="60%">
			<view class="popup-header">
				<view @tap="cancelWorkPerson">取消</view>
				<view @tap="confirmWorkPerson">确定</view>
			</view>
			<view class="popup-body">
				<scroll-view scroll-y="true" style="height:100%">
					<view>
						<view class="item" v-for="(item, index) in showPersonList" :key="index" @click="onSelectWorkPerson(item, index)" :class="{ selected: item.isSelect }">
							<view class="name">{{ item.nickName }} {{ item.remark ? '(' + item.remark + ')' : '' }}
							</view>
							<view class="icon iconfont">{{ item.isSelect ? '&#xeaef;' : '&#xead9;' }}</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		convertToLabelValueList
	} from '@/const/utils.js'
	import {
		ARCHIVES_TYPE,
		ARCHIVES_TYPE_NAMES
	} from '@/const/archives/index.js'
	import {
		checkType
	} from '@/common/utils/common.js'
	import {
		createFile,
		getLocalArchivesDetail,
		updateArchivesTime,
		getLocalModule
	} from '@/static/common/js/padLocalFileHandler.js'
	// import databaseModule from '@/static/common/js/dbUtils.js'
	import {
		mapGetters,
		mapMutations
	} from "vuex"
	import {
		getArchivesListByEnvironment
	} from '@/common/environmentalApi/index.js'
	export default {
		name: 'ArchiveAdd',
		data() {
			return {
				ARCHIVES_TYPE_NAMES,
				arrowList: ['案卷基本信息', '案卷其他信息'],
				stepIndex: 0,
				isFormRequired: false,
				form: {
					name: '',
					archivesType: ARCHIVES_TYPE.COMMONLY,
					archivesTypeText: ARCHIVES_TYPE_NAMES[ARCHIVES_TYPE.COMMONLY],
					category: ARCHIVES_TYPE.COMMONLY,
					fireAddress: '',
					fireAddressText: '',
					address: ''
				},
				rules: {
					name: [{
						required: true,
						message: '请输入档案名称',
						trigger: 'blur',
					}],
					archivesType: [{
						required: true,
						message: '请选择程序类型',
						trigger: 'blur',
						type: 'number'
					}],
					code: [{
						required: true,
						message: '请选择编号',
						trigger: 'blur'
					}],
				},
				fireInvestigationTypesObj: {
					show: false,
					list: convertToLabelValueList(ARCHIVES_TYPE, ARCHIVES_TYPE_NAMES)
				},
				timeObj: {
					type: 'call',
					show: false,
					defaultTime: new Date(),
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true,
						timestamp: true
					}
				},
				workPersonObj: {
					type: 'host',
					show: false,
					list: [],
					hostList: [],
					assistList: [],
					currentObj: {}
				},
				submitLoading: false,
				params: {}
			}
		},
		computed: {
			...mapGetters(['isNetworkConnected']),
			selectAssistPerson() {
				return params => {
					return this.workPersonObj.assistList
						.filter(item => item.isSelect)
						.map(person => person[params])
						.join(',');
				};
			},
			showPersonList() {
				return this.workPersonObj.type == 'host' ? this.workPersonObj.hostList : this.workPersonObj.assistList;
			},
			formatAddress() {
				return address => {
					if (!address || !address.length) return '--';
					if (checkType(address) === 'string') {
						return address.split(',')[2]
					} else if (checkType(address) === 'array') {
						return address[2];
					}
				};
			},
			archivesTypeList() {
				const list = convertToLabelValueList(ARCHIVES_TYPE, ARCHIVES_TYPE_NAMES).map(item => {
					if (item.value == this.form.archivesType) {
						return {
							...item,
							type: 'primary'
						}
					}
					return {
						...item,
						type: 'info'
					}
				})
				return list

			}
		},
		watch: {
			form: {
				handler(val) {
					if (val.name && (val.archivesType || val.archivesType == 0) && val.code) {
						this.isFormRequired = true
					}
				},
				deep: true
			}
		},
		onLoad(params) {
			uni.hideTabBar()
			this.params = params
			const isConnected = this.isNetworkConnected;
			this.getWorkPersonData()

			if (isConnected) {
				if (params.id) {
					this.getCoordinate(true);
				} else {
					this.getCoordinate();
				}
			}

			if (params.id) {
				getLocalArchivesDetail(params.id).then(data => {
					this.form = {
						...data,
						archivesTypeText: ARCHIVES_TYPE_NAMES[data.archivesType],
						fireAddressText: this.formatAddress(data.fireAddress),
						doPersonName: data.doPerson,
						doOtherPersonName: data.doOtherPerson,
					}
				})
			}

			uni.$on('selectMap', data => {
				const {
					location,
					name,
					address
				} = data;
				const locations = location.split(',');
				this.currentLocations = location;
				this.coordinateConvert({
					longitude: locations[0],
					latitude: locations[1]
				}, true);
				this.form.fireAddress = `${location},${address || ''}`;
				this.form.fireAddressText = `${address || ''}`;
				this.form.address = `${address || ''}${name}`;
				this.$forceUpdate();
			});
		},
		onUnload() {
			uni.$off('selectMap');
		},
		onReady() {
			this.$refs.addForm.setRules(this.rules);
		},
		onNavigationBarButtonTap(e) {
			this.form = {}
			uni.navigateBack()
		},
		methods: {
			...mapMutations(['SET_BASIC_INFO']),
			async getArchivesData(archivesId) {
				let res = await this.$u.api.archives.info({
					archivesId
				});
				let data = res.data
				this.form = {
					...data,
					archivesTypeText: ARCHIVES_TYPE_NAMES[data.archivesType],
					fireAddressText: this.formatAddress(data.fireAddress),
					doPersonName: data.doPerson,
					doOtherPersonName: data.doOtherPerson,
				}
			},
			onTagChange(item) {
				this.form.archivesType = item.value
				this.form.category = item.value
			},
			getWorkPersonData() {
				const userList = this.vuex_basicData.allUserList || []
				let list = userList.map(person => {
					return {
						...person,
						isSelect: false
					};
				});
				this.workPersonObj.list = list;
				this.workPersonObj.hostList = this.$u.deepClone(list);
				this.workPersonObj.assistList = this.$u.deepClone(list);
				return
				this.$u.api.systemUser
					.list({
						status: 0,
						pageNum: 1,
						pageSize: 999
					})
					.then(res => {
						if (res.code == 200) {
							let list = res.rows.map(person => {
								return {
									...person,
									isSelect: false
								};
							});

						}
					});
			},
			getCoordinate(isEdit = false) {
				let geocode = true;
				uni.getLocation({
					type: 'gcj02',
					geocode,
					isHighAccuracy: true,
					timeout: 30,
					// highAccuracyExpireTime: 4000,
					success: location => {
						let {
							longitude,
							latitude
						} = location;

						this.coordinateConvert({
							longitude: longitude,
							latitude: latitude,
						}, isEdit);

					},
					fail: err => {
						console.error(err);
					},
				});
			},
			coordinateConvert({
				longitude,
				latitude
			}, isEdit = false) {
				this.$u.api.GaodeApi.coordinateConvert({
					key: '9670df2781265a076d02bd0aaf33dc1a',
					locations: longitude + ',' + latitude // 经度在前，纬度在后
				}).then(res => {
					if (res.status == 1) {
						this.currentLocations = res.locations;
						this.$u.api.GaodeApi.inverseGeocode({
							key: '9670df2781265a076d02bd0aaf33dc1a',
							location: res.locations
						}).then(geocode => {
							const {
								addressComponent,
								formatted_address
							} = geocode.regeocode;
							const {
								province,
								city,
								district,
								township,
								streetNumber: {
									street,
									number,
									location
								}
							} = addressComponent;
							this.getWeather(city);
							if (!isEdit) {
								let fireAddress =
									`${province}${city}${district}${township}${street}${number}`
								this.form.address = formatted_address
								this.form.fireAddress = `${location},${fireAddress}`;
								this.form.fireAddressText = fireAddress
							}
						});
					}
				});
			},
			getWeather(location, date) {
				if (!date) {
					this.$u.api.GaodeApi.weather({
						key: '9670df2781265a076d02bd0aaf33dc1a',
						city: location,
						extensions: 'base',
						output: 'JSON'
					}).then(res => {
						if (res.status == 1) {
							const {
								weather,
								winddirection,
								windpower,
								humidity,
								temperature
							} = res.lives[0];
							this.form.weather =
								`天气${weather},${winddirection}风${windpower}级,空气湿度${humidity},实时气温${temperature}`;
						}
					});
				} else {
					this.$u.api.qweather.getCityInfo(location).then(res => {
						if (res.code == 200) {
							const LocationID = res.location[0].id;
							let dateTime = this.$u.timeFormat(date, 'yyyymmdd');
							this.$u.api.qweather
								.history({
									location: LocationID,
									date: dateTime
								})
								.then(weatherRes => {
									let historyData = weatherRes;
									let currentWeather = historyData.weatherHourly.filter(item => {
										let timeFormat = this.$u.timeFormat(item.time,
											'yyyy-mm-dd hh');
										let goTime = this.$u.timeFormat(date, 'yyyy-mm-dd hh');

										if (goTime == timeFormat) {
											return item;
										}
									});
									const {
										text,
										windDir,
										windScale,
										humidity,
										temp
									} = currentWeather[0];
									this.form.weather =
										`天气${text},${windDir}${windScale}级,空气湿度${humidity},实时气温${temp}`;
								})
								.catch(e => {
									console.error(e);
								});
						}
					});
				}
			},
			showTips() {
				this.$refs.uToast.show({
					title: '天气随出警时间与地点变化',
					type: 'primary',
				});
			},
			navTo(url) {
				if (this.currentLocations) {
					uni.navigateTo({
						url: url + `?locations=${this.currentLocations}`
					});
				} else {
					this.$refs.uToast.show({
						title: '请等待地理位置获取',
						type: 'primary',
					});
				}
			},
			onShowTimePicker(type) {
				this.timeObj.type = type;
				this.timeObj.defaultStartTime = this.form[type];
				this.timeObj.show = true;
			},
			confirmTimePicker(e) {
				let timeFormat = this.$u.timeFormat(e.timestamp * 1000, 'yyyy-mm-dd hh:MM:ss');
				if (this.timeObj.type == 'callTime') {
					this.form.callTime = timeFormat;
				} else {
					this.form.goTime = timeFormat;
					this.getWeather(this.currentLocations, timeFormat);
				}
			},
			onShowTypePopup() {
				this.fireInvestigationTypesObj.show = true;
			},
			confirmArchivesType(e) {
				let {
					value,
					label
				} = e[0];
				this.form.archivesType = value;
				this.form.category = value;
				this.form.archivesTypeText = label;
			},
			onShowPersonPopup(type) {
				this.workPersonObj.type = type;
				this.workPersonObj.show = true;
			},
			onSelectWorkPerson(item, index) {
				if (this.workPersonObj.type == 'host') {
					this.workPersonObj.hostList.forEach((person, i) => {
						person.isSelect = false;
						if (item.userId == person.userId) {
							this.$set(this.workPersonObj.hostList, i, {
								...person,
								isSelect: true
							});
						}
					});

					this.workPersonObj.currentObj = {
						name: item.nickName,
						id: item.userId,
						item
					};
				} else if (this.workPersonObj.type == 'assist') {
					let flag = !item.isSelect;
					this.workPersonObj.assistList.forEach((person, i) => {
						if (item.userId == person.userId) {
							item.isSelect = flag;
							this.$set(this.workPersonObj.assistList, i, person);
						}
					});
					this.workPersonObj.currentObj = {
						name: this.selectAssistPerson('nickName'),
						id: this.selectAssistPerson('userId')
					};
				}
			},
			confirmWorkPerson() {
				let {
					name,
					id,
					item
				} = this.workPersonObj.currentObj;
				if (this.workPersonObj.type == 'host') {
					// this.form.doPerson = id
					this.form.doOrg = item?.dept?.deptName || this.form.doOrg
					this.form.doPerson = id;
					this.form.doPersonName = name;
				} else {
					// this.form.doOtherPerson = id
					this.form.doOtherPerson = id;
					this.form.doOtherPersonName = name;
				}
				this.workPersonObj.show = false;
			},
			cancelWorkPerson() {
				this.workPersonObj.show = false;
			},

			initForm() {
				let form = {
					name: '滨江区先锋科技大厦重大火灾案',
					fireName: '高楼大厦',
					callTime: this.$u.timeFormat(1654321813, 'yyyy-mm-dd hh:MM:ss'),
					goTime: this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd hh:MM:ss'),
					archivesType: '0',
					category: 0,
					archivesTypeText: '简易程序',
					weather: '天气多云，南风4级，空气湿度6',
					doOrg: '滨江区消防大队',
					doPerson: '曹队长', //方便测试一次性提交
					doPersonName: '曹队长',
					doOtherPerson: '唐伯虎', //方便测试一次性提交
					doOtherPersonName: '唐伯虎',
					doCars: '2',
					doPersonCount: '9',
					state: '0',
					fireAddress: '',
					fireAddressText: '',
					address: ''
				}
				return form
			},
			importData() {
				let formData = this.initForm()
				let json = JSON.parse(JSON.stringify(this.initForm()))
				this.form = Object.assign({}, this.form, json);
			},
			nextStep() {
				if (this.stepIndex == 1) {
					this.stepIndex--
				} else {
					this.$refs.addForm.validate(valid => {
						if (valid) {

							this.stepIndex++
						}
					})
				}
			},
			async submit() {
				// this.submitLoading = true;
				this.$refs.addForm.validate(async valid => {
					if (valid) {
						this.submitLoading = false;
						let addressArr = this.form.fireAddress.split(',')
						addressArr[2] = this.form.fireAddressText
						this.form.fireAddress = addressArr.join(',')
						if (!this.isNetworkConnected) {
							this.form.doPerson = this.form.doPersonName
							this.form.doOtherPerson = this.form.doOtherPersonName
						}
						let id = await createFile(this.form)
						await getLocalModule(id, this.form.archivesType)
						let archivesList = await getArchivesListByEnvironment({}, true)
						this.SET_BASIC_INFO({
							archivesList
						})

						await updateArchivesTime(id)
						this.submitLoading = false;

						uni.setStorage({
							key: 'archivesId',
							data: id
						});
						uni.$emit('archivesId', id);
						this.$u.vuex('vuex_archives', {
							archivesId: id
						});
						var pages = getCurrentPages(); // 当前页面
						var beforePage = pages[pages.length - 2]; // 前一个页面
						if (beforePage.route == 'pages/sys/home/index') {
							uni.redirectTo({
								url: '/pages/sys/detail/index'
							});
						} else {
							uni.navigateBack({
								delta: 1
							});
						}
						return
						// if (!this.isNetworkConnected) {
						// 打开数据库连接
						// await databaseModule.openSqlite();
						// // 创建表
						// const tableDefinition = 'id INTEGER PRIMARY KEY, name TEXT, age INTEGER';
						// await databaseModule.createTable('person', tableDefinition);

						// // 插入数据
						// const data = 'NULL, "John Doe", 30'; // 使用 NULL 作为自增主键的占位值
						// await databaseModule.insertTableData('person', data);

						// // 查询数据
						// const conditions = ['age > 25'];
						// const results = await databaseModule.selectTableData('person', conditions);

						// // 关闭数据库连接
						// await databaseModule.closeSqlite();
						// }
					} else {
						// 验证失败
						this.submitLoading = false;
					}
				});
			},
		}
	}
</script>
<style scoped lang="scss">
	.archives-add-page {}

	.main {
		padding: 20rpx;

		.main-container {
			background-color: #fff;

			.footer {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;

				.btns {
					padding: 20rpx 0;
					width: 50%;
					display: flex;
					justify-content: space-around;

					button {
						flex: 1;
						margin: 0 20rpx;
					}
				}
			}

		}
	}

	.step-list {
		display: flex;
		align-items: center;
		justify-content: center;
		padding-top: 20rpx;

		.step {
			position: relative;
			height: 100%;

			&:last-child {
				.line {
					display: none;
				}
			}

			.step-box {
				text-align: center;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				--outline-width: 10rpx;
				--circle-diameter: 20rpx;
				--step-width: 100%;
				--all-circle: calc((var(--outline-width) * 2 + var(--circle-diameter)));
				--half-width: calc((var(--step-width) - var(--all-circle)) / 2);

				&.active {
					.circle {
						background-color: $u-type-primary;
						box-shadow: 0 0 0 var(--outline-width) lighten($u-type-primary, 32%);
					}
				}

				.step {
					width: var(--step-width);
				}

				.circle {
					margin: var(--outline-width);
					width: var(--circle-diameter);
					height: var(--circle-diameter);
					border-radius: 50%;
					background-color: $u-type-info;
					box-shadow: 0 0 0 var(--outline-width) lighten($u-type-info, 18%);
				}

				.line {
					width: calc(100% - var(--all-circle));
					position: absolute;
					left: calc(var(--half-width) + var(--all-circle));
					top: calc(var(--outline-width) + (var(--circle-diameter) / 2));
					background-color: #1B7DD4;
					height: 4rpx;
				}
			}
		}
	}


	.step-content {
		.step-content-container {
			padding: 0 20rpx;
			background-color: #fff;
			/* #ifdef H5 */
			//页面视图总高度 -顶部导航栏 - 上下边距 - 步骤条 - 底部按钮
			height: calc(100vh - 44px - 40rpx - 49px - 66px);
			/* #endif */
			overflow: hidden;
		}

		.base-info-tit {
			font-weight: bold;
			font-size: 32rpx;
		}

		.step-item {
			overflow-y: auto;
		}
	}

	::v-deep .u-form-item--right__content__slot {
		position: relative;
		height: 90upx;

		.tags-wrap {
			width: 100%;
			display: flex;
			justify-content: flex-end;

			.tag {
				margin-left: 16rpx;
			}
		}

		.wrap {
			position: absolute;
			display: flex;
			justify-content: space-around;
			width: 100%;

			.left-tit {
				display: flex;
				align-items: center;
			}
		}
	}


	.work-person-popup {
		.popup-header {
			width: 100%;
			height: 92rpx;
			padding: 0 40rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			box-sizing: border-box;
			font-size: 30rpx;
			background: #fff;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				border-bottom: 0.5px solid #eaeef1;
				-webkit-transform: scaleY(0.5);
				transform: scaleY(0.5);
				bottom: 0;
				right: 0;
				left: 0;
			}
		}

		.popup-body {
			height: calc(100% - 92upx);
			padding: 10upx 20upx 20upx;

			.item {
				height: 100upx;
				border-bottom: 1px solid $u-form-item-border-color;
				color: $u-tips-color;
				display: flex;
				align-items: center;
				justify-content: space-between;

				&.selected {
					color: $u-type-primary;
				}

				.name {
					font-size: 38upx;
				}

				.icon {
					font-size: 50upx;
				}
			}
		}
	}
</style>